/*
 * Copyright 2013 The Scripps Research Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.scripps.fl.entrez.internal;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import edu.scripps.fl.entrez.ELinkResult;

public class ELinkHandler extends DefaultHandler {
	private ELinkResult result;
	private List<Long> idList;
	private StringBuffer buf;
	private int depth;
	private String linkName;
	private String dbTo;
	private Collection<ELinkResult> relations;

	public ELinkHandler(Collection<ELinkResult> relations) {
		this.relations = relations;
	}

	public void characters(char ch[], int start, int length) throws SAXException {
		buf.append(ch, start, length);
	}

	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (qName.equalsIgnoreCase("LinkSet"))
			relations.add(result);
		else if (qName.equalsIgnoreCase("LinkSetDb")) {
			if (idList.size() > 0)
				result.setIds(dbTo, linkName, idList);
		} else if (qName.equalsIgnoreCase("LinkName"))
			linkName = buf.toString();
		else if (qName.equalsIgnoreCase("dbTo"))
			dbTo = buf.toString();
		else if (qName.equalsIgnoreCase("DbFrom"))
			result.setDbFrom(buf.toString());
		else if (qName.equalsIgnoreCase("Id")) {
			Long id = Long.parseLong(buf.toString());
			if (depth == 4)
				result.setId(id);
			else if (depth == 5)
				idList.add(id);
		}
		depth--;
	}

	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		depth++;
		buf = new StringBuffer();
		if (qName.equalsIgnoreCase("LinkSet"))
			result = new ELinkResult();
		else if (qName.equalsIgnoreCase("LinkSetDb"))
			idList = new ArrayList();
	}
}